<template>
  <span v-if="isShowProject" @click="clickProject" class="project_name sle">{{ currentProject }}</span>
  <el-select
      v-if="!isShowProject"
      v-model="currentProject"
      @change="setCurrentProject"
      @blur="isShowProject=true"
      ref="projectSelectInput"
      filterable
      placeholder="Select"
      style="width: 240px"
  >
    <el-option
        v-for="item in selectProjectList"
        :key="item.id"
        :label="item.project_name"
        :value="item.id"
    />
  </el-select>

<!--  <el-dropdown max-height="300" trigger="click" @command="setCurrentProject">-->
<!--    <span class="project_name sle">{{ currentProject }}</span>-->
<!--    <template #dropdown>-->
<!--      <el-dropdown-menu>-->
<!--        <el-dropdown-item-->
<!--            v-for="item in selectProjectList"-->
<!--            :key="item.id"-->
<!--            :command="item.id"-->
<!--            :disabled="false"-->
<!--        >-->
<!--          {{ item.project_name }}-->
<!--        </el-dropdown-item>-->
<!--      </el-dropdown-menu>-->
<!--    </template>-->
<!--  </el-dropdown>-->

</template>

<script setup>

import {nextTick, onBeforeUnmount, onMounted, ref} from "vue";
import {useProjectStore} from "@/stores/modules/project/project.js";
import {storeToRefs} from "pinia";

const projectStore = useProjectStore()
const {currentProject, currentProjectId, selectProjectList} = storeToRefs(projectStore)

onMounted(() => {
  projectStore.getSelectProjectList()
})

const isShowProject = ref(true)
const projectSelectInput = ref()

const clickProject = ()=>{
  isShowProject.value = false
  nextTick(()=>{
    projectSelectInput.value.focus()
  })
}

const setCurrentProject = (projectId) => {
  currentProjectId.value = projectId
  selectProjectList.value.forEach(projectItem => {
    if (projectItem.id === projectId) {
      currentProject.value = projectItem.project_name
    }
  })
  isShowProject.value = true
//   触发当前选中项目事件
  $eventBus.emit("updateCurrentProject")

}


onMounted(()=>{
  $eventBus.on("updateProject",async ()=>{
    console.log("updateProject")
    await projectStore.getSelectProjectList()
    console.log(selectProjectList.value)
  })
})

onBeforeUnmount(()=>{
  $eventBus.off("updateProject")
})

</script>

<style lang="scss">

.project_name {
  max-width: 200px;
  padding: 10px 0;
  color: var(--el-color-primary-light-3);

  &:hover {
    color: var(--el-color-primary);
    cursor: pointer;
    //font-size: 20px;
  }
}

</style>
